import 'dart:async';
import 'dart:typed_data';
import 'dart:io';

import 'package:flutter/services.dart';
import 'package:plugin_ocr/bean/ocr_results.dart';
import 'dart:convert';
import 'package:image/image.dart' as img;
import 'package:path_provider/path_provider.dart';
import 'package:uuid/uuid.dart';

import 'bean/ocr_result.dart';

class PluginOcr {
  static const MethodChannel _channel = const MethodChannel('plugin_ocr');

  static Future<String> get platformVersion async {
    final String version = await _channel.invokeMethod('getPlatformVersion');
    return version;
  }

  static Future<OcrResultInfo> ocrFromImage(String imagePath, {bool isRotate = false,bool forwardRotation = true,double degree = 90.0, String ocr_type}) async {
    String ocrImagePath = imagePath;
    if (isRotate) {
      var imageData = File(imagePath).readAsBytesSync();
      img.Image image = img.decodeImage(imageData);
      img.Image ocrImage = img.copyRotate(image, forwardRotation?degree:-degree);
      Directory dir = await getExternalStorageDirectory();
      String path = dir.path;
      File rotate90ImageFile = File('$path/rotate/${Uuid().v4().toString()}.jpg');
      rotate90ImageFile.parent.createSync(recursive: true);
      rotate90ImageFile.writeAsBytesSync(img.encodeJpg(ocrImage));
      ocrImagePath = rotate90ImageFile.path;
    }
    final String ocrStr = await _channel.invokeMethod('ocrFromImage', {'imagePath': ocrImagePath});
    return _processOcrResult(ocrStr, ocr_type: ocr_type);
  }

  static Future<OcrResultInfo> get ocr async {
    final String ocrStr = await _channel.invokeMethod('ocr');
    return _processOcrResult(ocrStr);
  }

  static Future<OcrResultInfo> _processOcrResult(String ocrStr, {String ocr_type}) async {
    OcrResultInfo ocrResultInfo = OcrResultInfo.fromJson({'ocrResults': jsonDecode(ocrStr), 'ocr_type': 'OTHER'});
    ocrResultInfo.ocrResults.forEach((element) {
      print(element.toString());
    });
    if (ocrResultInfo.ocrResults.length == 0) {
      ocrResultInfo.ocr_type = 'EMPTY';
      return ocrResultInfo;
    }
    List<OcrResult> ocrResults = [];
    int index = 0;
    if (ocr_type != null) {
      ocrResultInfo.ocr_type = ocr_type;
    }
    for (var i = 0; i < ocrResultInfo.ocrResults.length; i++) {
      OcrResult ocrResult = ocrResultInfo.ocrResults[i];
      String content = ocrResult.name;
      if (content.contains('姓名')) {
        if (ocr_type == null) {
          ocrResultInfo.ocr_type = 'ID_CARD';
        }
        if (content.length > 2) {
          ocrResults
              .add(OcrResult(index: index, name: content.substring(content.indexOf('姓名') + 2), bounds: ocrResult.bounds, confidence: ocrResult.confidence));
          index++;
        }
      } else if (content.contains('性别') && content.length > 2) {
        ocrResults.add(OcrResult(
            index: index,
            name: content.substring(content.indexOf('性别') + 2, content.indexOf('性别') + 3),
            bounds: ocrResult.bounds,
            confidence: ocrResult.confidence));
        index++;
        if (content.contains('民族')) {
          ocrResults
              .add(OcrResult(index: index, name: content.substring(content.indexOf('民族') + 2), bounds: ocrResult.bounds, confidence: ocrResult.confidence));
          index++;
        }
      } else if (content.contains('出生') && content.length > 2) {
        ocrResults.add(OcrResult(index: index, name: content.substring(content.indexOf('出生') + 2), bounds: ocrResult.bounds, confidence: ocrResult.confidence));
        index++;
      } else if (content.contains('公民身份号码') && content.length > 6) {
        if (ocr_type == null) {
          ocrResultInfo.ocr_type = 'ID_CARD';
        }
        ocrResults
            .add(OcrResult(index: index, name: content.substring(content.indexOf('公民身份号码') + 6), bounds: ocrResult.bounds, confidence: ocrResult.confidence));
        index++;
      } else if (ocrResultInfo.ocr_type == 'ID_CARD' && content.length == 18 && content.contains(new RegExp(r'[0-9xX]{18}'))) {
        ocrResults.insert(4, OcrResult(index: index, name: content, bounds: ocrResult.bounds, confidence: ocrResult.confidence));
        index++;
      } else if (ocrResultInfo.ocr_type != 'ID_CARD' && content.length >= 16 && content.contains(new RegExp(r'[0-9]{16,}'))) {
        if (ocr_type == null) {
          ocrResultInfo.ocr_type = 'BANK_CARD';
        }
        print('银行卡号:$content');
        ocrResults.clear();
        if (content.startsWith('62')) {
          ocrResults.add(OcrResult(index: 0, name: content, bounds: ocrResult.bounds, confidence: ocrResult.confidence));
        }
        break;
      } else if (content != '公民身份号码' && content != '住址') {
        ocrResults.add(OcrResult(index: index, name: content, bounds: ocrResult.bounds, confidence: ocrResult.confidence));
        index++;
      }
    }
    if (ocrResultInfo.ocr_type == 'ID_CARD') {
      String addr = '';
      for (var i = 0; i < ocrResults.length; i++) {
        if (i > 4) {
          addr += ocrResults[i].name;
        }
      }
      ocrResults.removeRange(5, ocrResults.length);
      ocrResults.add(OcrResult(index: 5, name: addr));
    }
    ocrResultInfo.ocrResults = ocrResults;
    return ocrResultInfo;
  }
}
